package zaplog

import (
	"os"
	"path/filepath"
	"time"

	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

func (l *Logger) debugCore(encoder zapcore.Encoder) zapcore.Core {
	lvlEnabler := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
		return lev >= l.config.Level
	})
	return zapcore.NewCore(encoder, zapcore.Lock(os.Stderr), lvlEnabler)
}

func (l *Logger) fileCore(encoder zapcore.Encoder) zapcore.Core {
	path, err := filepath.Abs(l.file.FilePath)
	if err != nil {
		panic(err)
	}
	if err := os.MkdirAll(path, 0755); err != nil {
		panic(err)
	}

	// info和debug级别,debug级别是最低的
	accessWriter := writeSyncer(path, "access.log")
	accessEnabler := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
		return lev >= l.config.Level && lev < zapcore.ErrorLevel
	})
	accessCore := zapcore.NewCore(encoder, accessWriter, accessEnabler)
	// error级别
	errorWriter := writeSyncer(path, "error.log")
	errorEnabler := zap.LevelEnablerFunc(func(lev zapcore.Level) bool {
		return lev >= l.config.Level && lev >= zapcore.ErrorLevel
	})
	errorCore := zapcore.NewCore(encoder, errorWriter, errorEnabler)

	return zapcore.NewTee(accessCore, errorCore)
}

func writeSyncer(path, fileName string) zapcore.WriteSyncer {
	file := filepath.Join(path, fileName)
	log, err := rotatelogs.New(
		file+"-%Y%m%d%H",
		rotatelogs.WithLinkName(file), // 生成软链，指向最新日志文件
		//MaxAge and RotationCount cannot be both set  两者不能同时设置
		rotatelogs.WithMaxAge(time.Hour*24*30), // clear 最小分钟为单位
		//rotatelogs.WithRotationCount(5),        // number 默认7份 大于7份 或到了清理时间 开始清理
		rotatelogs.WithRotationTime(time.Minute), // rotate 最小为1分钟轮询。默认60s  低于1分钟就按1分钟来
	)
	if err != nil {
		panic(err)
	}
	return zapcore.Lock(zapcore.AddSync(log))
}
